package cn.com.dashihui.web.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresAuthentication;

import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;

import cn.com.dashihui.kit.CommonKit;
import cn.com.dashihui.kit.DatetimeKit;
import cn.com.dashihui.kit.ExcelExportUtil.Pair;
import cn.com.dashihui.kit.UtilNumber;
import cn.com.dashihui.web.base.BaseController;
import cn.com.dashihui.web.dao.AdSeller;
import cn.com.dashihui.web.dao.AuthDownload;
import cn.com.dashihui.web.dao.Seller;
import cn.com.dashihui.web.dao.Store;
import cn.com.dashihui.web.dao.User;
import cn.com.dashihui.web.dao.UserChange;
import cn.com.dashihui.web.dao.UserValueLog;
import cn.com.dashihui.web.service.AuthDownloadService;
import cn.com.dashihui.web.service.ChangeDeliveryService;
import cn.com.dashihui.web.service.UserService;

@RequiresAuthentication
public class ChangeDeliveryController extends BaseController{
	private ChangeDeliveryService service = new ChangeDeliveryService();
	private UserService userService = new UserService();
	private AuthDownloadService downloadService=new AuthDownloadService();

    /**
     * 查询所有公司返回index页面
     */
    public void index(){
    	List<Seller> sellerList = service.findAllSeller();
    	List<Record> ListChangeScale = service.findChangeScale();
    	setAttr("ListChangeScale", ListChangeScale);
		setAttr("sellerList", sellerList);
        render("index.jsp");
    }
    /**
     * 查询所有配送日志
     */
    public void history(){
    	List<Seller> sellerList = service.findAllSeller();
    	List<Record> ListChangeScale = service.findChangeScale();
    	setAttr("ListChangeScale", ListChangeScale);
		setAttr("sellerList", sellerList);
        render("history.jsp");
    }
    /**
	 * 选择分公司
	 */
	public void chooseStore(){
		String[] seller = getParaValues("seller");
		String str = java.lang.String.join("','", seller);
		renderSuccess(service.chooseStore(str));
	}
	/**
	 * 选择营业部
	 */
	public void chooseDao(){
		String[] store = getParaValues("store");
		String str = java.lang.String.join("','", store);
		renderSuccess(service.chooseDao(str));
	}
    /**
     * 查询页面数据，并返回页面显示
     */
    public void page(){
    	int pageNum = getParaToInt(0, 1);
		String phone=getPara("phone");
		String card=getPara("card");
		String sellerid=getPara("seller");//所属公司
		int match=getParaToInt("match",0);
		int toBossThreeId = 0 ;
		if (StrKit.notBlank(sellerid)) {
			//根据dao分公司名称查询营业部id
			Seller seller = userService.findSellerById(sellerid);
			toBossThreeId = seller.get("id");
		}
		String storeid=getPara("store");//所属分公司
		int toBossTwoId = 0 ;
		if (StrKit.notBlank(storeid)) {
			//根据dao分公司名称查询营业部id
			Store store = userService.findStoreById(storeid);
			toBossTwoId = store.get("id");
		}
		String dao=getPara("dao");
		int toBossOneId = 0 ;
		if (StrKit.notBlank(dao)) {
			//根据dao分公司名称查询营业部id
			AdSeller adSeller = userService.findAdSellerByName(dao);
			toBossOneId = adSeller.get("id");
		} 

		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		renderResult(0,service.findByPage(pageNum, pageSize,phone,card,toBossThreeId,toBossTwoId,toBossOneId,match));
	}
    /**
	 * 会员积分统计
	 */
	public void page1(){
		String index=getPara("index");
		int pageNum = getParaToInt(0, 1);
		String phone=getPara("phone");
		String card=getPara("card");
		String sellerid=getPara("seller");//所属公司
		int toBossThreeId = 0 ;
		if (StrKit.notBlank(sellerid)) {
			//查询公司
			Seller seller = userService.findSellerById(sellerid);
			toBossThreeId = seller.get("id");
		}
		String storeid=getPara("store");//所属分公司
		int toBossTwoId = 0 ;
		if (StrKit.notBlank(storeid)) {
			//查询分公司
			Store store = userService.findStoreById(storeid);
			toBossTwoId = store.get("id");
		}
		String dao=getPara("dao");
		int toBossOneId = 0 ;
		if (StrKit.notBlank(dao)) {
			//根据dao分公司名称查询营业部id
			AdSeller adSeller = userService.findAdSellerByName(dao);
			toBossOneId = adSeller.get("id");
		} 
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		renderResult(0,service.findByPages1(pageNum, pageSize,index,phone,card,toBossThreeId,toBossTwoId,toBossOneId));
	}
    /**
	 * 前往预览页面
	 */
	public void toView(){
		//以手机号为唯一基准
		String ids=getPara("adIds");
		String[] sid = ids.split(",");
		//获取兑换一次所需的数量
		int num=getParaToInt("num");
		//获取兑换所需种类
		int type=getParaToInt("type");
		List<Object> list = new ArrayList<>();
		for (int i = 0; i < sid.length; i++) {
			Map<String, String> map=new HashMap<String,String>();
			String phone = sid[i];
			User user = service.findByUserPhone(phone);
			String username = user.get("name");
			/*int ecoupon = user.get("ecoupon");
			if (ecoupon != 0) {
				renderFailed(username+"的电子券不为零，请优先配送");
				return;
			}*/
			UserChange userChange = service.findChangeByPhone(phone);
			String clientCode =null;
			if (userChange!=null) {
				clientCode = userChange.get("clientCode");
			}
			
			if (type == 1) {
				int sppoint = user.getInt("sppoint");
				int deliveryNum = (sppoint / num);
				if (deliveryNum == 0) {
					renderFailed(username+"的可转换次数为零，请去除");
					return;
				}
				int payPoint = (deliveryNum * num);
				int remainPoint = (sppoint - payPoint);
				String sDeliveryNum = deliveryNum+"";
				String sPayPoint = "" + payPoint;
				String sRemainPoint = "" + remainPoint;
				map.put("deliveryNum", sDeliveryNum);
				map.put("payPoint", sPayPoint);
				map.put("remainPoint", sRemainPoint);
			}
			if (type == 2) {
				int jkpoint = user.getInt("jkpoint");
				int deliveryNum = (jkpoint / num);
				if (deliveryNum == 0) {
					renderFailed(username+"的可转换次数为零，请去除");
					return;
				}
				int payPoint = (deliveryNum * num);
				int remainPoint = (jkpoint - payPoint);
				String sDeliveryNum = deliveryNum+"";
				String sPayPoint = "" + payPoint;
				String sRemainPoint = "" + remainPoint;
				map.put("deliveryNum", sDeliveryNum);
				map.put("payPoint", sPayPoint);
				map.put("remainPoint", sRemainPoint);
			}
			if (type == 3) {
				int jypoint = user.getInt("jypoint");
				int deliveryNum = (jypoint / num);
				/*if (deliveryNum == 0) {
					renderFailed(username+"的可转换次数为零，请去除");
					return;
				}*/
				int payPoint = (deliveryNum * num);
				int remainPoint = (jypoint - payPoint);
				String sDeliveryNum = deliveryNum+"";
				String sPayPoint = "" + payPoint;
				String sRemainPoint = "" + remainPoint;
				map.put("deliveryNum", sDeliveryNum);
				map.put("payPoint", sPayPoint);
				map.put("remainPoint", sRemainPoint);
			}
			if (clientCode!=null) {
				map.put("clientCode", clientCode);
			}
			map.put("phone", phone);
			
			map.put("username", username);
			list.add(map);
		}	
		setAttr("type", type);
		setAttr("list", list);
		setAttr("ids", ids);
		render("view.jsp");
	}
	/**
	 * 转换，进行对应积分消减，兑换个数存入数据库
	 */
    public void doDelivery(){
    	
    	int type = getParaToInt("type");
    	String[] sDeliveryNum = getParaValues("deliveryNum");
    	String[] sPayPoint = getParaValues("payPoint");
    	String[] sRemainPoint = getParaValues("remainPoint");
    	String[] sPhone = getParaValues("phone");
    	if (sDeliveryNum != null && sDeliveryNum.length > 0) {
			for (int i = 0; i < sDeliveryNum.length; i++) {
				String phone = sPhone[i];
				String deliveryNum = sDeliveryNum[i];
				String payPoint = sPayPoint[i];
				String remainPoint = sRemainPoint[i];
				User user = userService.findByPhone(phone);
				String username= user.get("name");
				int ecoupon = user.get("ecoupon");
				if (ecoupon != 0) {
					renderFailed(username+"的电子券不为零，请优先配送");
					return;
				}
				System.out.println(deliveryNum);
				int intdeliveryNum = Integer.valueOf(deliveryNum).intValue();
				System.out.println(intdeliveryNum);
				if (intdeliveryNum == 0) {
					renderFailed(username+"的可转换次数为零，请去除");
					return;
				}
				System.out.println(user);
//				user.set("ecoupon", Integer.valueOf(deliveryNum).intValue())//电子券数量
				user.set("ecoupon", intdeliveryNum)//电子券数量
									;
				if (user.update()) {
					//在更新之前获取用户的三种积分值，作为日志里面的历史值
					double sppointHistory = user.getDouble("sppoint");
					double deduHistory = user.getDouble("jkpoint");
					double couponHistory = user.getDouble("jypoint");
					double ecouponHistory = user.getDouble("ecoupon");
					if (type == 1) {
						user.set("sppoint",  UtilNumber.DoubleValueOf(remainPoint));
					}
					if (type == 2) {
						user.set("jkpoint",  UtilNumber.DoubleValueOf(remainPoint));
					}
					if (type == 3) {
						user.set("jypoint",  UtilNumber.DoubleValueOf(remainPoint));
					}
					if (user.update()) {
						UserValueLog userValueLog = new UserValueLog();
						int userid = user.getInt("id");
						
						int logType = 2;
						int flag = 9;
						int data = 1;
						String describe = "配送转换消耗";
						String orderNumStore = "ZH"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
						userValueLog.set("userid", userid).set("type", logType).set("flag", flag).set("fromOrderNum", orderNumStore)
							.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss")).set("data", data).set("describe", describe)
							.set("sppointHistory", sppointHistory).set("deduHistory", deduHistory).set("couponHistory", couponHistory)
							.set("ecoupon", deliveryNum).set("ecouponHistory", ecouponHistory);
						if (type == 1) {
							userValueLog.set("sppoint",  UtilNumber.DoubleValueOf(payPoint));
						}
						if (type == 2) {
							userValueLog.set("dedu",  UtilNumber.DoubleValueOf(payPoint));
						}
						if (type == 3) {
							userValueLog.set("coupon",  UtilNumber.DoubleValueOf(payPoint));
						}
						userValueLog.save();
					}else {
						renderFailed("写入日志失败");
						return;
					}
				}else {
					renderFailed("更新用户积分失败");
					return;	
				}
			}
			renderSuccess();
		}
    }
    /**
	 * excel导出配送
	 */
	public void doDeliveryExcel(){
		List<Pair> titles = new ArrayList<Pair>();
		//以手机号为唯一基准
		String ids=getPara("adIds");
		String[] sid = ids.split(",");
		//获取兑换一次所需的数量
		/*int num=getParaToInt("num");
		//获取兑换所需种类
		int type = getParaToInt("type");*/
		
	    titles.add(new Pair("clientCode", "转入方编号"));
	    titles.add(new Pair("username", "转入方名称"));
	    titles.add(new Pair("deliveryNum", "数量"));
	    titles.add(new Pair("bankNoId", "手续费"));
	    titles.add(new Pair("payPoint", "消耗"));
		List<Record> listz=new ArrayList<Record>();
		if (sid != null && sid.length > 0) {
			for (int i = 0; i < sid.length; i++) {
			Record record=new Record();
			String phone = sid[i];
			User user = service.findByUserPhone(phone);
			String username = user.get("name");
			int ecoupon = user.getInt("ecoupon");
			if (ecoupon == 0) {
				renderFailed("会员" + username + "没有电子券，请移除");
				continue;
			}
			int userid = user.getInt("id");
			UserValueLog userValueLog = service.findUserValueLog(userid);
			System.out.println(userValueLog);
			double coupon = userValueLog.getDouble("coupon");
			System.out.println(coupon);
			String sCoupon = "惠券" + coupon;
			UserChange userChange = service.findChangeByPhone(phone);
			if (userChange == null) {
				renderFailed("会员" + username + "没有同步，请移除");
				continue;
			}
			String clientCode = userChange.get("clientCode");
			String sEcoupon = null ;
			sEcoupon = ecoupon+"";
			/*String sPayPoint = null ;
			if (type == 1) {
				int payPoint = (ecoupon * num);
				
				sPayPoint = "积分" + payPoint;
			}
			if (type == 2) {
				int payPoint = (ecoupon * num);
				sEcoupon = ecoupon+"";
				sPayPoint = "抵扣券" + payPoint;
			}
			if (type == 3) {
				int payPoint = (ecoupon * num);
				sEcoupon = ecoupon+"";
				sPayPoint = "惠券" + payPoint;
			}*/
				record.set("clientCode", clientCode);
				record.set("username",username);
				record.set("deliveryNum", sEcoupon);
				record.set("payPoint", sCoupon);	
			listz.add(record);
			user.set("ecouponState", 0);
			user.set("ecoupon", 0);
			user.update();
			}
		}
		//向登录下载统计表中添加数据 会员积分统计
		Record downObj=downloadService.findByUserId(getCurrentUser().getInt("id"));
		AuthDownload download=new AuthDownload();
		download.set("logName","平台端")
			        .set("name", downObj.get("trueName"))
			        .set("accountRole", downObj.get("alias"))
			        .set("storeName", "公司总部")
			        .set("integralDownload", 1)
                   .set("downloadDate",DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
		download.save();
		// 导出
		service.export(getResponse(), getRequest(),titles, listz);		
		renderNull();
	}
	/**
	 * excel导出
	 */
	public void doExcel(){
		List<Pair> titles = new ArrayList<Pair>();
		String phone=getPara("phone");
		String card=getPara("card");
		String match = getPara("match");
		titles.add(new Pair("clientCode", "匹配编码"));
	    titles.add(new Pair("phone", "客户名称"));
	    titles.add(new Pair("userType", "客户类型"));
	    titles.add(new Pair("name", "法人代表"));
	    titles.add(new Pair("bankNoId", "开户银行"));
	    titles.add(new Pair("cardNo", "银行账号"));
	    titles.add(new Pair("userType", "证件类型"));
	    titles.add(new Pair("cardIdNo", "证件号"));  
	    titles.add(new Pair("phone", "手机"));
	    titles.add(new Pair("email", "邮箱"));
	    titles.add(new Pair("address", "详细地址"));
	    titles.add(new Pair("toBossOneId", "推荐人"));
	    titles.add(new Pair("createDate", "担保商"));
		List<Record> list=service.findExcelByPage(phone,card,match);
		List<Record> listz=new ArrayList<Record>();
		for (int i = 0; i < list.size(); i++) {
			Record record=new Record();
				record.set("clientCode", list.get(i).get("clientCode"));
				record.set("phone", list.get(i).get("phone"));
				record.set("userType",list.get(i).get("userType"));
				record.set("name", list.get(i).get("name"));
				record.set("bankNoId", list.get(i).get("bankNoId"));
				record.set("cardIdNo", list.get(i).get("cardIdNo"));
				record.set("userType",list.get(i).get("userType"));
				record.set("cardNo", list.get(i).get("bankCardNo"));
				record.set("phone", list.get(i).get("phone"));
				record.set("email", list.get(i).get("email"));
				record.set("address", list.get(i).get("address"));
			listz.add(record);
 		}
		//向登录下载统计表中添加数据 会员积分统计
		Record downObj=downloadService.findByUserId(getCurrentUser().getInt("id"));
		AuthDownload download=new AuthDownload();
		download.set("logName","平台端")
			        .set("name", downObj.get("trueName"))
			        .set("accountRole", downObj.get("alias"))
			        .set("storeName", "公司总部")
			        .set("integralDownload", 1)
                   .set("downloadDate",DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));

		download.save();
		// 导出
		service.exportChange(getResponse(), getRequest(),titles, listz);		
		renderNull();
	}
	 /**
     * 查询所有配送比例记录返回index页面
     */
	public void pageScale(){
    	int pageNum = getParaToInt(0, 1);
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		renderResult(0,service.findByPageScale(pageNum, pageSize));
	}
	
	/**
	 * 添加配送比例
	 */
	public void toAdd() {
		String scaleValue=getPara("scaleValue");
		String date=getPara("date");
		if (StrKit.isBlank(scaleValue)) {
			renderFailed("参数scaleValue为空");
			return;
		}
		if (StrKit.isBlank(date)) {
			renderFailed("参数date为空");
			return;
		}
		//日期判断
		Date date1=new Date();
		if (Integer.valueOf(date)==2) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(new Date());
			cal.add(Calendar.DATE, -1);
			date1=cal.getTime();
		}
		String date2=DatetimeKit.getFormatDate(date1, "yyyy-MM-dd");
		Record record=service.findScaleByDate(date2);
		if (record!=null) {
			renderFailed("该日期已添加，请勿重复添加");
			return;
		}
		//添加记录
		Record re=new Record();
		re.set("scaleValue", Integer.valueOf(scaleValue)).set("date", date1);
		if (service.addScale(re)) {
			renderSuccess();
		} else {
			renderFailed();
		};
		
	}
	/**
	 * 打开修改页面
	 */
	public void toUpdate() {
		String id=getPara("id");
		if (StrKit.isBlank(id)) {
			renderFailed("参数id为空");
			return;
		}
		setAttr("id", id);
		render("view.jsp");
	}
	/**
	 * 修改配送比例
	 */
	public void doUpdate() {
		String id=getPara("id");
		String scaleValue=getPara("num");
		if (StrKit.isBlank(id)) {
			renderFailed("参数id为空");
			return;
		}
		if (StrKit.isBlank(scaleValue)) {
			renderFailed("参数scaleValue为空");
			return;
		}
		Record scale=service.findScaleByID(Integer.valueOf(id));
		if (scale!=null) {
			scale.set("scaleValue", scaleValue);
		}
		if (service.scaleUpdate(scale)) {
			renderSuccess();
		}else {
			renderFailed("修改配送比例失败");
		}
	}
}
